package com.frogs.ucenter.v1.service.impl;

import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.frogs.framework.base.dao.BaseDao;
import com.frogs.framework.base.service.daoimpl.BaseServiceImpl;
import com.frogs.framework.util.PageList;

import com.frogs.system.util.SwitchEnum;

import com.frogs.system.web.api.request.Request;
import com.frogs.system.web.api.response.Response;
import com.frogs.system.web.exception.ServiceOperationException;
import com.frogs.ucenter.dao.SeedUserInfoDao;
import com.frogs.ucenter.dao.UserBaseInfoDao;
import com.frogs.ucenter.entity.SeedUserInfo;
import com.frogs.ucenter.entity.UserBaseInfo;
import com.frogs.ucenter.v1.request.SeedAddrRequest;
import com.frogs.ucenter.v1.request.SeedPayRequest;
import com.frogs.ucenter.v1.request.SeedRequest;
import com.frogs.ucenter.v1.response.DefaultResponse;
import com.frogs.ucenter.v1.service.SeedUserInfoService;
import com.frogs.ucenter.v1.util.ApiConstants;

@Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
@Service(ApiConstants.VERSION + "seedUserInfoService")
public class SeedUserInfoServiceImpl extends BaseServiceImpl<SeedUserInfo>
		implements SeedUserInfoService {

	private static final Logger log = LoggerFactory
			.getLogger(SeedUserInfoServiceImpl.class);

	@Autowired
	private SeedUserInfoDao seedUserInfoDao;
	
	@Autowired
	private UserBaseInfoDao userBaseInfoDao;

	public SeedUserInfoServiceImpl() {
		super();
	}

	public SeedUserInfoDao getSeedUserInfoDao() {
		return seedUserInfoDao;
	}

	/**
	 * Don't remove or edit it.
	 */
	@Override
	protected BaseDao<SeedUserInfo> getBaseDao() {
		return seedUserInfoDao;
	}

	public void setSeedUserInfoDao(SeedUserInfoDao seedUserInfoDao) {
		this.seedUserInfoDao = seedUserInfoDao;
	}

	@Override
	public Response addSeedUser(Request request) throws Exception {
		Response response = new DefaultResponse();
		Map<String, Object> params = new HashMap<String, Object>();
		try {
			SeedRequest sdreq = (SeedRequest) request;
			SeedUserInfo su = new SeedUserInfo();
			su.setUserId(sdreq.getUserId());
			su.setOpenId(sdreq.getOpenId());
			su.setWechatAccount(sdreq.getWechatAccount());
			su.setWechatNickName(sdreq.getWechatNickName());
			su.setIsLook(sdreq.getIsLook());
			su.setIsPay(sdreq.getIsPay());
			su.setSubjectId(sdreq.getSubjectId());
			su.setCreateTime(new Date());

			params.put("eqOpenId", su.getOpenId());
			params.put("eqUserId", su.getUserId());

			PageList<SeedUserInfo> seedUserInfo = seedUserInfoDao.selectByMap(
					params, 0, 999, false);
			if (seedUserInfo.size() == 0) {
				seedUserInfoDao.insert(su);
				log.info("SeedUserInfoServiceImpl.addSeedUser=userID："
						+ su.getUserId() + " 新增访客");
			} else {
				params.put("eqIsPay", 0);
				PageList<SeedUserInfo> seedUserInfo1 = seedUserInfoDao.selectByMap(
						params, 0, 999, false);
				if (seedUserInfo1.size() != 0) {
					response.setTip("添加失败,已有记录存在");

				} else {
					seedUserInfoDao.insert(su);
					log.info("SeedUserInfoServiceImpl.addSeedUser=userID："
							+ su.getUserId() + " 新增访客");
				}
			}

		} catch (Exception e) {
			log.error(
					"func[{}] request[{}] exception[{}] desc[fail]",
					new Object[] {
							this.getClass().getName()
									+ "."
									+ Thread.currentThread().getStackTrace()[1]
											.getMethodName(),
							Arrays.deepToString(e.getStackTrace()) });
			throw new ServiceOperationException("请求处理失败：" + e.getMessage());

		}

		return response;
	}

	@Override
	public Response addSeedPay(Request request) throws Exception {
		Response response = new DefaultResponse();
		Map<String, Object> params = new HashMap<String, Object>();
		try {
			SeedPayRequest sdreq = (SeedPayRequest) request;

			params.put("eqOpenId", sdreq.getOpenId());
			params.put("eqUserId", sdreq.getUserId());
			params.put("eqIsPay", 0);
			
			PageList<SeedUserInfo> seedUserInfoList = seedUserInfoDao.selectByMap(params, 0, 999, false);

			SeedUserInfo seedUserInfo=seedUserInfoList.get(0);
			
			seedUserInfo.setIsPay(sdreq.getIsPay());
			seedUserInfo.setSeedTime(new Date());
			seedUserInfo.setPayPrice(sdreq.getPayPrice());
			
			seedUserInfoDao.update(seedUserInfo);

			log.info("SeedUserInfoServiceImpl.addSeedPay=userID："
					+ sdreq.getUserId() + " 更新种子用户支付信息");

		} catch (Exception e1) {
			log.error(
					"func[{}] request[{}] exception[{}] desc[fail]",
					new Object[] {
							this.getClass().getName()
									+ "."
									+ Thread.currentThread().getStackTrace()[1]
											.getMethodName(),
							Arrays.deepToString(e1.getStackTrace()) });
			throw new ServiceOperationException("请求处理失败：" + e1.getMessage());

		}

		return response;
	}

	@Override
	public Response addSeedAddr(Request request) throws Exception {
		Response response = new DefaultResponse();
		Map<String, Object> params = new HashMap<String, Object>();
		try {
			//前提用户必须要有访问记录（必须要已存在用户的情况，这里要看一下情况）
			SeedAddrRequest sdreq = (SeedAddrRequest) request;

			params.put("eqOpenId", sdreq.getOpenId());
			params.put("eqUserId", sdreq.getUserId());
			params.put("eqIsPay", SwitchEnum.NO.getId());
			
			PageList<SeedUserInfo>seedUserInfoList=seedUserInfoDao.selectByMap(params, 1, 1, false);
			
			if(seedUserInfoList.size() > 0) {
				SeedUserInfo seedUserInfo=seedUserInfoList.get(0);
				seedUserInfo.setPhone(sdreq.getContactNumber());
				seedUserInfo.setRealName(sdreq.getContacts());
				seedUserInfo.setUserAddress(sdreq.getUserAddress());

				seedUserInfoDao.update(seedUserInfo);
				log.info("SeedUserInfoServiceImpl.addSeedPay=userID："
						+ sdreq.getUserId() + " 更新种子用户个人信息");
				
				params.clear();
				params.put("eqId", sdreq.getUserId());
				PageList<UserBaseInfo>userBaseInfoList=userBaseInfoDao.selectByMap(params, 0, 999, false);
				UserBaseInfo userBaseInfo=userBaseInfoList.get(userBaseInfoList.size()-1);
				userBaseInfo.setDefaultPhone(sdreq.getPhone());
				userBaseInfo.setRealName(sdreq.getRealName());
				
				userBaseInfoDao.update(userBaseInfo);
				log.info("SeedUserInfoServiceImpl.addSeedPay=userID："
						+ sdreq.getUserId() + " 更新用户基本信息的手机和真名");
			} else {
				SeedUserInfo seedUserInfo = new SeedUserInfo();
				seedUserInfo.setIsPay(SwitchEnum.NO.getId());
				seedUserInfo.setOpenId(sdreq.getOpenId());
				seedUserInfo.setRealName(sdreq.getContacts());
				seedUserInfo.setPhone(sdreq.getContactNumber());
				seedUserInfo.setUserAddress(sdreq.getFullAddress());
				seedUserInfo.setUserId(sdreq.getUserId());
				//种子用户活动，写死3，有时间再改成枚举
				seedUserInfo.setSubjectId("3");
				seedUserInfo.setIsLook(SwitchEnum.YES.getId());
				seedUserInfo.setCreateTime(new Date());
				seedUserInfo.setPayPrice(0);
				seedUserInfoDao.insert(seedUserInfo);
				log.info("SeedUserInfoServiceImpl.addSeedPay=userID："
						+ sdreq.getUserId() + " 插入种子用户个人信息");
				
				params.clear();
				params.put("eqId", sdreq.getUserId());
				PageList<UserBaseInfo>userBaseInfoList=userBaseInfoDao.selectByMap(params, 0, 999, false);
				UserBaseInfo userBaseInfo=userBaseInfoList.get(userBaseInfoList.size()-1);
				userBaseInfo.setDefaultPhone(sdreq.getPhone());
				userBaseInfo.setRealName(sdreq.getRealName());
				
				userBaseInfoDao.update(userBaseInfo);
				log.info("SeedUserInfoServiceImpl.addSeedPay=userID："
						+ sdreq.getUserId() + " 更新用户基本信息的手机和真名");
			}
			

			
		} catch (Exception e1) {
			log.error(
					"func[{}] request[{}] exception[{}] desc[fail]",
					new Object[] {
							this.getClass().getName()
									+ "."
									+ Thread.currentThread().getStackTrace()[1]
											.getMethodName(),
							Arrays.deepToString(e1.getStackTrace()) });
			throw new ServiceOperationException("请求处理失败：" + e1.getMessage());

		}

		return response;
	}

}